package com.oa.admin.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.oa.admin.mapper.SysUserTokenMapper;
import com.oa.admin.service.ISysUserTokenService;
import com.oa.system.entity.SysUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken> implements ISysUserTokenService {

    @Autowired
    private SysUserTokenMapper userTokenMapper;

    @Override
    public SysUserToken queryByToken(String accessToken) {
        SysUserToken userToken = new SysUserToken();
        userToken.setAccessToken(accessToken);
        return userTokenMapper.selectOne(userToken);
    }

    @Override
    public SysUserToken createToken(String userId) {
        Date now=new Date();
        //生成token
        String token = generateToken();
        SysUserToken userToken = new SysUserToken();
        userToken.setUserId(userId);
        userToken.setAccessToken(token);
        userToken.setLastUpdateTime(now);
        //判断token是否为空
        if(null!=this.selectById(userId)){
            updateById(userToken);
        }else{
            //保存或更新用户token
            insert(userToken);
        }
        return userToken;
    }

    @Override
    public SysUserToken refreshToken(String userId) {
        Date now=new Date();
        SysUserToken userToken = new SysUserToken();
        userToken.setUserId(userId);
        userToken.setAccessToken(generateToken());
        userToken.setLastUpdateTime(now);
        this.updateById(userToken);
        return userToken;
    }

    @Override
    public void removeToken(String userId) {
        Date now=new Date();
        SysUserToken userToken = new SysUserToken();
        userToken.setUserId(userId);
        userToken.setAccessToken(null);
        userToken.setLastUpdateTime(now);
        this.updateById(userToken);
    }

    @Override
    public void refreshTokenTime(String userId) {
        Date now=new Date();
        //生成token
        SysUserToken userToken = new SysUserToken();
        userToken.setUserId(userId);
        userToken.setAccessToken(generateToken());
        userToken.setLastUpdateTime(now);
        this.updateById(userToken);
    }

    private String generateToken(){
        return UUID.randomUUID().toString().replace("-", "");
    }
}
